<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <form>
      <input
        type="file"
        name="avatar"
        accept="image/*"
        placeholder="请选择头像"
      />
      <button>上传文件</button>
    </form>
    <img src="" alt="" class="avatar" style="width: 500px" />
  </body>
  <script src="./js/axios.js"></script>
  <script>
    // 获取元素
    const form = document.querySelector('form')
    const avatar = document.querySelector('.avatar')

    // form绑定提交事件
    form.addEventListener('submit', function (e) {
      // 阻止表单默认提交行为
      e.preventDefault()

      // new关键词进行实例化，实例化时传入form表单，自动获取数据
      const fn = new FormData(form)

      // 发出请求
      axios
        .post('http://ajax-api.itheima.net/api/file', fn)
        // 响应数据
        .then(({ data: res }) => {
          
          //  接收图片的url地址
          const url = res.data.url
          // console.log(url);

          // 替换
          avatar.src = url
        })
    })
  </script>
</html>
